package main

import (
	"context"
	"fmt"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// TimePoint 任务的执行时间
type TimePoint struct {
	StartTime int64 `bson:"startTime"`
	EndTime   int64 `bson:"endTime"`
}

// LogRecord 一条日志
type LogRecord struct {
	JobName   string    `bson:"jobName"`   // 任务名
	Command   string    `bson:"command"`   // shell命令
	Err       string    `bson:"err"`       // 脚本错误
	Content   string    `bson:"content"`   // 脚本输出
	TimePoint TimePoint `bson:"timePoint"` // 执行时间点
}

// FindByJobName JobName过滤条件
type FindByJobName struct {
	JobName string `bson:"jobName"`
}

func main() {
	client := ConnToMongo(context.TODO(), "mongodb://10.0.0.11:27017")

	// 2. 选择数据库、选择表
	coll := client.Database("my_db").Collection("today")

	// 3. 查询
	cond := &FindByJobName{JobName: "job10"}
	cur, err := coll.Find(context.TODO(), cond)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer cur.Close(context.TODO())
	for cur.Next(context.TODO()) {
		record := &LogRecord{}
		if err := cur.Decode(record); err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(record)
	}
}

func ConnToMongo(ctx context.Context, url string) *mongo.Client {
	client, err := mongo.Connect(ctx, options.Client().ApplyURI(url))
	if err != nil {
		panic(err)
	}

	return client
}
